<script lang="ts" setup>
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from "@/store/user";
import { computed, reactive, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { ICurrentMenu, IMeta, ITagsViewRouter } from "@/utils/types/TMenu.ts";
import {
  hideTagview,
  hideTagviewEndsWith,
  NOT_FOUNT_STATUS,
} from "@/utils/const.ts";

const currentRoute = useRoute();
const router = useRouter();
const userStore = useUserStore();

const state = reactive({
  activeKey: currentRoute.fullPath,
  contextMenuVisible: false,
  menuLeft: 0,
  menuTop: 0,
  menuDisabled: {
    all: false,
    curr: false,
    left: false,
    right: false,
  },
});
const menuCurrent = ref<ICurrentMenu>();
const two = 2;
const twney = 20;

watch(
  () => currentRoute.fullPath,
  (to: string) => {
    setTimeout(() => {
      state.activeKey = to;
      userStore.addTags(currentRoute);
    }, 0);
  },
  { immediate: true },
);
// 标签页列表
const { tabsList } = storeToRefs(userStore);

const currTitle = computed(() => (pane?: ITagsViewRouter) => {
  const {
    meta: { title },
    fullPath,
  }: ITagsViewRouter = pane || {
    fullPath: currentRoute.fullPath,
    meta: { title: currentRoute.meta.title } as IMeta,
  };
  if (title.startsWith("新建")) {
    if (fullPath.indexOf("update") !== NOT_FOUNT_STATUS) {
      return title.replace("新建", "编辑");
    }
  }
  return title;
});

const hideTitleBlock = computed(
  () =>
    hideTagview.includes(currentRoute.fullPath) ||
    hideTagviewEndsWith.filter(item => {
      return currentRoute.fullPath.endsWith(item);
    }).length,
);

//  判断是否是当前选中的上一项
const isPrevitem = computed(() => (index: number) => {
  const idx = tabsList.value.findIndex(
    (item: ITagsViewRouter) => item.fullPath === state.activeKey,
  );
  if (idx !== NOT_FOUNT_STATUS) {
    return idx === index + 1 ? true : false;
  }
  return false;
});
const changeTab = (key: string) => {
  state.activeKey = key;
  router.push(key);
};

// 关闭当前页面
const removeTab = (route: ITagsViewRouter) => {
  userStore.closeCurrentTag(route);
  if (tabsList.value.length === 1) {
    router.push("/home");
    return;
  }
  // 如果关闭的是当前页
  if (state.activeKey === route.fullPath) {
    const currentRoute1: ITagsViewRouter =
      tabsList.value[Math.max(0, tabsList.value.length - 1)];
    state.activeKey = currentRoute1.fullPath || "";
    router.push(currentRoute1);
  }
};
const closeTabItem = (targetKey: string) => {
  removeTab(
    tabsList.value.find(
      (item: ITagsViewRouter) => item.fullPath === targetKey,
    ) as ITagsViewRouter,
  );
};

//隐藏菜单
const closeMenu = () => {
  state.contextMenuVisible = false;
};

watch(
  () => state.contextMenuVisible,
  (val: boolean) => {
    if (val) {
      document.body.addEventListener("click", closeMenu);
    } else {
      document.body.removeEventListener("click", closeMenu);
    }
  },
);
//显示右击菜单
const openContextMenu = (e: MouseEvent, item: ITagsViewRouter, idx: number) => {
  e.preventDefault(); //防止默认菜单弹出
  menuCurrent.value = {
    ...item,
    idx,
  };
  if (idx === 0) {
    // 工作台
    state.menuDisabled.curr = true;
    state.menuDisabled.left = true;
    if (tabsList.value.length === 1) {
      state.menuDisabled.right = true;
      state.menuDisabled.all = true;
    } else {
      state.menuDisabled.right = false;
      state.menuDisabled.all = false;
    }
  } else if (idx === 1) {
    // 工作台后一个
    state.menuDisabled.curr = false;
    state.menuDisabled.left = true;
    if (tabsList.value.length > two) {
      state.menuDisabled.right = false;
    } else {
      state.menuDisabled.right = true;
    }
  } else {
    if (idx === tabsList.value.length - 1) {
      state.menuDisabled.right = true;
    } else {
      state.menuDisabled.right = false;
    }
    state.menuDisabled.curr = false;
    state.menuDisabled.left = false;
    state.menuDisabled.all = false;
  }
  state.contextMenuVisible = true;
  //返回鼠标坐标点，并传递给菜单的绝对定位值
  state.menuLeft = e.clientX;
  state.menuTop = e.clientY + twney;
};

const menuCloseHandle = (type: string) => {
  const { fullPath, idx } = menuCurrent.value;
  if (type === "curr") {
    closeTabItem(fullPath);
  } else if (type === "all") {
    userStore.closeAllTags();
    router.push("/home");
  } else if (type === "left") {
    userStore.closeLeftTags(idx);
    router.push(fullPath);
  } else if (type === "right") {
    userStore.closeRightTags(idx);
    router.push(fullPath);
  }
};

const reload = () => {
  // console.log("reload");
};
</script>

<template>
  <div style="background: #f6f7f9">
    <div class="tab-block">
      <div
        v-for="(pane, idx) in tabsList"
        :key="pane.fullPath"
        :class="
          state.activeKey === pane.fullPath
            ? 'tab-item active'
            : idx === tabsList.length - 1 || isPrevitem(idx)
              ? 'tab-item'
              : 'tab-item line'
        "
        @click="changeTab(pane.fullPath)"
        @contextmenu.prevent="e => openContextMenu(e, pane, idx)"
      >
        <div
          style="
            padding-right: 5px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          "
        >
          {{ currTitle(pane) }}
        </div>
        <JIcon
          v-if="pane.fullPath != '/home'"
          class="close-icon"
          style="font-size: 10px; color: rgb(0 0 0 / 30%); cursor: pointer"
          type="icon-ic_label_close"
          @click.stop="closeTabItem(pane.fullPath)"
        />
      </div>
    </div>
    <div v-if="!hideTitleBlock" class="title-block">
      {{ currTitle() }}
      <a-button style="float: right" @click="reload">
        <JIcon
          style="font-size: 14px; color: rgb(0 0 0 / 65%); cursor: pointer"
          type="icon-ic_refresh"
        />
        刷新
      </a-button>
    </div>
    <div v-show="state.contextMenuVisible">
      <ul
        :style="{ left: state.menuLeft + 'px', top: state.menuTop + 'px' }"
        class="contextmenu"
      >
        <li :class="state.menuDisabled.curr ? 'disable' : ''">
          <a-button
            :disabled="state.menuDisabled.curr"
            size="mini"
            type="text"
            @click="menuCloseHandle('curr')"
          >
            关闭当前
          </a-button>
        </li>
        <li :class="state.menuDisabled.right ? 'disable' : ''">
          <a-button
            :disabled="state.menuDisabled.right"
            size="mini"
            type="text"
            @click="menuCloseHandle('right')"
          >
            关闭右侧
          </a-button>
        </li>
        <li :class="state.menuDisabled.left ? 'disable' : ''">
          <a-button
            :disabled="state.menuDisabled.left"
            size="mini"
            type="text"
            @click="menuCloseHandle('left')"
          >
            关闭左侧
          </a-button>
        </li>
        <li :class="state.menuDisabled.all ? 'disable' : ''">
          <a-button
            :disabled="state.menuDisabled.all"
            size="mini"
            type="text"
            @click="menuCloseHandle('all')"
          >
            关闭所有
          </a-button>
        </li>
      </ul>
    </div>
  </div>
</template>
<style lang="less" scoped>
.title-block {
  padding: 16px 30px;
  font-size: 18px;
  color: #000;
  background: #fff;
  box-shadow: 0 -2px 5px 1px rgb(0 0 0 / 5%);
}

.close-icon {
  padding: 5px;
  border-radius: 50%;

  &:hover {
    background: #e5e5e5;
  }
}

.tab-block {
  display: flex;
  height: 40px;
  padding: 0 10px;
  overflow: auto hidden;

  .tab-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex: 0 0 138px;
    width: 138px;
    height: 32px;
    padding: 0 15px;
    margin-top: 8px;
    line-height: 32px;
    color: #37363e;
    cursor: pointer;

    &.line {
      position: relative;

      &::after {
        position: absolute;
        right: 0;
        width: 1px;
        height: 18px;
        background: rgb(0 0 0 / 45%);
        content: "";
      }
    }

    &.active {
      flex: 0 0 153px;
      width: 153px;
      padding: 0 30px;
      color: #000;
      background: url("@/assets/tab_bg.png") bottom;
    }
  }
}

::-webkit-scrollbar {
  width: 5px;
  height: 2px;
}

::-webkit-scrollbar-thumb {
  background: rgb(0 0 0 / 20%);
  border-radius: 10px;
}

::-webkit-scrollbar-track {
  border-radius: 10px;
}

.contextmenu {
  position: absolute;
  z-index: 3000;
  padding: 5px 0;
  margin: 0;
  font-size: 14px;
  color: #333;
  list-style-type: none;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 2px 2px 3px 0 rgb(0 0 0 / 20%);
}

.contextmenu li.disable {
  color: #999;
}

.contextmenu li:hover {
  cursor: pointer;
  background: #f2f2f2;
}
</style>
